package com.sys.core.shiro;


import com.sys.core.utils.ListUtils;
import com.sys.core.utils.LocalDateTime;
import com.sys.user.domain.XyMenu;
import com.sys.user.domain.Xyrole;
import com.sys.user.domain.Xyuser;
import com.sys.user.service.XyMenuService;
import com.sys.user.service.XyroleService;
import com.sys.user.service.XyuserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Sha1Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 汤伟杰 on 2017/6/17.
 */
@Component
//    @Repository
public class MyRealm extends AuthorizingRealm {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private XyuserService xyuserService;
    @Autowired
    private XyroleService xyroleService;
    @Autowired
    private XyMenuService xyMenuService;


    public MyRealm() {
        super();
        //设置认证token的实现类
        setAuthenticationTokenClass(UsernamePasswordToken.class);
        //设置加密算法
        setCredentialsMatcher(new HashedCredentialsMatcher(Sha1Hash.ALGORITHM_NAME));

    }
    /**
     * 登录成功后为访问需要授权的资源时，没有授权信息，则运行这里，获取授权
     * 为当前登录的Subject授予角色和权限
     *   经测试:本例中该方法的调用时机为需授权资源被访问时
     *   经测试:并且每次访问需授权资源时都会执行该方法中的逻辑,这表明本例中默认并未启用AuthorizationCache
     *   个人感觉若使用了Spring3.1开始提供的ConcurrentMapCache支持,则可灵活决定是否启用AuthorizationCache
     *   比如说这里从数据库获取权限信息时,先去访问Spring3.1提供的缓存,而不使用Shior提供的AuthorizationCache
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){
        //获取当前登录的用户名,等价于(String)principals.fromRealm(this.getName()).iterator().next()
        String currentUsername = (String)super.getAvailablePrincipal(principals);
      List<String> roleList = new ArrayList<String>();
      List<String> permissionList = new ArrayList<String>();
      //从数据库中获取当前登录用户的详细信息
      Xyuser user = xyuserService.getByUsername(currentUsername);
      if(null != user){
          List<Xyrole> xyroleList = xyroleService.queryByUserId(user.getUserId());
          //角色集合
          List<String> roleIdList = new ArrayList<String>();
          //实体类User中包含有用户角色的实体类信息
          for (Xyrole xyrole : xyroleList) {
              roleList.add(xyrole.getName());
              roleIdList.add(xyrole.getRoleId());
          }
          List<XyMenu> xypermissionList =  xyMenuService.queryByRoleIdIn(roleIdList);
          //url
          for (XyMenu vo : xypermissionList) {
              permissionList.add(vo.getNameEn());
          }
      }else{
          throw new AuthorizationException();
      }
//        permissionList.add("comments:list");
      //为当前用户设置角色和权限
      SimpleAuthorizationInfo simpleAuthorInfo = new SimpleAuthorizationInfo();
        ListUtils.removeDuplicateWithOrder(roleList);
        ListUtils.removeDuplicateWithOrder(permissionList);
      simpleAuthorInfo.addRoles(roleList);
      simpleAuthorInfo.addStringPermissions(permissionList);
        return simpleAuthorInfo;
    }


    /**
     * 验证当前登录的Subject
     *   经测试:本例中该方法的调用时机为LoginController.login()方法中执行Subject.login()时
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        //获取基于用户名和密码的令牌
        //实际上这个authcToken是从LoginController里面currentUser.login(token)传过来的
        //两个token的引用都是一样的

        UsernamePasswordToken upToken = (UsernamePasswordToken) authcToken;
        Xyuser user = xyuserService.getByUsername(upToken.getUsername());
        if (user != null) {
            this.setSession("adminuser",user);
            return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
        }
        return null;
    }


    /**
     * 将一些数据放到ShiroSession中,以便于其它地方使用
     *   比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到
     */
    private void setSession(Object key, Object value){
        Subject currentUser = SecurityUtils.getSubject();
        if(null != currentUser){
            Session session = currentUser.getSession();
            System.out.println(LocalDateTime.now()+" Session默认超时时间为[" + session.getTimeout() + "]毫秒");
            if(null != session){
                session.setAttribute(key, value);
            }
        }
    }



}